<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2024/3/20
 * Time: 14:16
 */

namespace app\common\lib;


use app\model\redis\RedisQueueModel;

class RedisQueue
{
    protected static $instance;

    public static function getInstance()
    {
        //        if(is_object(self::$instance)){
//            return self::$instance;
//        }


        return new self();
    }

    public function sendQueue($queue,$data,$connect='default')
    {
        $data['queueid'] = $this->saveQueue($queue,$data);

        // 投递消息
        \Webman\RedisQueue\Redis::connection($connect)->send($queue, $data);
    }

    public function saveQueue($queue,$data,$result=[])
    {
        if(!empty($data['queueid'])){
            $first = (new RedisQueueModel)->getWhere(['queueid'=>$data['queueid']])->first();
            if($first){
                $first->result = json_encode($result,256);
                $first->status = isset($result['error'])?2:1;
                $first->finish_at = date('Y-m-d H:i:s');
                return $first->save();
            }
            return false;
        }else{
            $insert = [
                'name'=>$queue,
                'data'=>json_encode($data,256),
                'status'=>0,
                'result'=>json_encode($result,256),
                'requestid'=>$data['requestid']??'',
            ];

            return (new RedisQueueModel)->insertGetId($insert);
        }
    }
}